package com.atguigu.ggkt.vod.service.impl;

import com.atguigu.ggkt.exception.GgktException;
import com.atguigu.ggkt.model.vod.*;
import com.atguigu.ggkt.vo.vod.*;
import com.atguigu.ggkt.vod.mapper.CourseMapper;
import com.atguigu.ggkt.vod.service.*;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 课程 服务实现类
 * </p>
 *
 * @author lxx
 * @since 2022-06-30
 */
@Service
public class CourseServiceImpl extends ServiceImpl<CourseMapper, Course> implements CourseService {
    @Autowired
    private TeacherService teacherService;
    @Autowired
    private SubjectService subjectService;
    @Autowired
    private CourseDescriptionService descriptionService;
    @Autowired
    private ChapterService chapterService;
    @Autowired
    private VideoService videoService;

    @Override
    public Map<String, Object> findPageCourse(Page<Course> page, CourseQueryVo courseQueryVo) {
        if (courseQueryVo == null) {
            page(page, null);
        } else {
            // 1.获取条件值
            // 一层分类
            Long subjectParentId = courseQueryVo.getSubjectParentId();
            // 二层分类
            Long subjectId = courseQueryVo.getSubjectId();
            Long teacherId = courseQueryVo.getTeacherId();
            String title = courseQueryVo.getTitle();
            // 2.封装查询条件
            LambdaQueryWrapper<Course> lqw = new LambdaQueryWrapper<>();
            lqw.eq(!StringUtils.isEmpty(subjectId), Course::getSubjectId, subjectId);
            lqw.eq(!StringUtils.isEmpty(subjectParentId), Course::getSubjectParentId, subjectParentId);
            lqw.eq(!StringUtils.isEmpty(teacherId), Course::getTeacherId, teacherId);
            lqw.like(!StringUtils.isEmpty(title), Course::getTitle, title);
            page(page, lqw);
        }
        // 3.获取查询分页信息
        List<Course> list = page.getRecords();
        // 获取id对应的名称，进行封装
        list.forEach(this::getNameById);
        long size = page.getSize();
        long total = page.getTotal();
        HashMap<String, Object> map = new HashMap<>(16);
        map.put("records", list);
        map.put("size", size);
        map.put("total", total);
        return map;
    }

    @Override
    public Long saveCourseInfo(CourseFormVo courseFormVo) {
        Course course = new Course();
        BeanUtils.copyProperties(courseFormVo, course);
        // 1.保存课程信息
        save(course);
        // 2.添加课程描述信息
        Long courseId = course.getId();
        String description = courseFormVo.getDescription();
        CourseDescription courseDescription = new CourseDescription();
        courseDescription.setCourseId(courseId);
        courseDescription.setDescription(description);
        descriptionService.save(courseDescription);
        return courseId;
    }

    @Override
    public CourseFormVo getCourseInfoById(Long id) {
        Course course = getById(id);
        if (course == null) {
            throw new GgktException(20001, "课程不存在");
        }
        LambdaQueryWrapper<CourseDescription> lqw = new LambdaQueryWrapper<>();
        lqw.eq(!StringUtils.isEmpty(course.getId()), CourseDescription::getCourseId, course.getId());
        CourseDescription courseDescription = descriptionService.getOne(lqw);
        CourseFormVo courseFormVo = new CourseFormVo();
        BeanUtils.copyProperties(course, courseFormVo);
        courseFormVo.setDescription(courseDescription.getDescription());
        return courseFormVo;
    }

    @Override
    public Long updateCourseInfo(CourseFormVo courseFormVo) {
        Long courseId = courseFormVo.getId();
        Course course = new Course();
        BeanUtils.copyProperties(courseFormVo, course);
        // 1.更新课程基本信息
        updateById(course);
        // 2.更新课程描述信息
        CourseDescription courseDescription = new CourseDescription();
        courseDescription.setDescription(courseFormVo.getDescription());
        courseDescription.setCourseId(courseId);
        // 2.1.封装更新条件
        LambdaUpdateWrapper<CourseDescription> luw = new LambdaUpdateWrapper<>();
        luw.eq(true, CourseDescription::getCourseId, courseId);
        luw.set(true, CourseDescription::getDescription, courseFormVo.getDescription());
        descriptionService.update(luw);
        return courseId;
    }

    @Override
    public CoursePublishVo getCoursePublishVo(Long id) {
        return baseMapper.selectCoursePublishVo(id);
    }

    @Override
    public void finalPublishCourse(Long id) {
        // 1.根据课程id更新课程状态,封装更新条件
        LambdaUpdateWrapper<Course> luw = new LambdaUpdateWrapper<>();
        luw.eq(Course::getId, id);
        luw.set(Course::getStatus, 1);
        luw.set(Course::getPublishTime, new Date());
        // 2.执行更新
        update(luw);
    }

    @Override
    public void deleteCourseById(Long id) {
        // 删除课程，还包括删除课程描述,章节，小节
        // 1.删除描述
        QueryWrapper<CourseDescription> qw01 = new QueryWrapper<>();
        qw01.eq("course_id", id);
        descriptionService.remove(qw01);
        // 2.删除小节和小节视频
        videoService.deleteVideoByCourseId(id);
        // 3.删除章节
        QueryWrapper<Chapter> qw02 = new QueryWrapper<>();
        qw02.eq("course_id", id);
        chapterService.remove(qw02);
        // 4.删除课程
        removeById(id);
    }

    @Override
    public Map<String, Object> findPage(Page<Course> pageParam, CourseQueryVo courseQueryVo) {
        // 获取条件值
        String title = courseQueryVo.getTitle(); // 名称
        Long subjectId = courseQueryVo.getSubjectId(); // 二级分类
        Long subjectParentId = courseQueryVo.getSubjectParentId(); // 一级分类
        Long teacherId = courseQueryVo.getTeacherId(); // 讲师
        // 封装条件
        QueryWrapper<Course> wrapper = new QueryWrapper<>();
        if(!StringUtils.isEmpty(title)) {
            wrapper.like("title",title);
        }
        if(!StringUtils.isEmpty(subjectId)) {
            wrapper.eq("subject_id",subjectId);
        }
        if(!StringUtils.isEmpty(subjectParentId)) {
            wrapper.eq("subject_parent_id",subjectParentId);
        }
        if(!StringUtils.isEmpty(teacherId)) {
            wrapper.eq("teacher_id",teacherId);
        }
        // 调用方法查询
        Page<Course> pages = baseMapper.selectPage(pageParam, wrapper);

        long totalCount = pages.getTotal(); // 总记录数
        long totalPage = pages.getPages(); // 总页数
        // 每页数据集合
        List<Course> records = pages.getRecords();
        records.stream().forEach(item -> {
            getTeacherOrSubjectName(item);
        });

        Map<String,Object> map = new HashMap<>();
        map.put("totalCount",totalCount);
        map.put("totalPage",totalPage);
        map.put("records",records);

        return map;
    }

    private Course getTeacherOrSubjectName(Course course) {
        Teacher teacher = teacherService.getById(course.getTeacherId());
        if(teacher != null) {
            course.getParam().put("teacherName",teacher.getName());
        }
        Subject subjectOne = subjectService.getById(course.getSubjectParentId());
        if(subjectOne != null) {
            course.getParam().put("subjectParentTitle",subjectOne.getTitle());
        }
        Subject subjectTwo = subjectService.getById(course.getSubjectId());
        if(subjectTwo != null) {
            course.getParam().put("subjectTitle",subjectTwo.getTitle());
        }
        return course;
    }

    @Override
    public Map<String, Object> getInfoById(Long id) {
        //更新流量量
        Course course = baseMapper.selectById(id);
        course.setViewCount(course.getViewCount() + 1);
        baseMapper.updateById(course);

        Map<String, Object> map = new HashMap<>();
        CourseVo courseVo = baseMapper.selectCourseVoById(id);
        List<ChapterVo> chapterVoList = chapterService.getTreeList(id);
        CourseDescription courseDescription = descriptionService.getById(id);
        Teacher teacher = teacherService.getById(course.getTeacherId());

        // TODO 后续完善
        // Boolean isBuy = false;

        map.put("courseVo", courseVo);
        map.put("chapterVoList", chapterVoList);
        map.put("description", null != courseDescription ?
                courseDescription.getDescription() : "");
        map.put("teacher", teacher);
        map.put("isBuy", false);// 是否购买
        return map;
    }


    private void getNameById(Course item) {
        // 1.根据讲师id获取名称
        Long teacherId = item.getTeacherId();
        Teacher teacher = teacherService.getById(teacherId);
        // 2.根据课程分类id获取分类名称
        Long subjectId = item.getSubjectId();
        Long subjectParentId = item.getSubjectParentId();
        // 2.1.一级分类
        Subject oneSubject = subjectService.getById(subjectParentId);
        // 2.2.二级分类
        Subject twoSubject = subjectService.getById(subjectId);
        if (teacher != null) {
            item.getParam().put("teacherName", teacher.getName());
        }
        if (oneSubject != null) {
            item.getParam().put("subjectParentTitle", oneSubject.getTitle());
        }
        if (twoSubject != null) {
            item.getParam().put("subjectTitle", twoSubject.getTitle());
        }
    }

    @Override
    public List<Course> findlist() {
        List<Course> list = baseMapper.selectList(null);
        list.stream().forEach(item -> {
            getTeacherOrSubjectName(item);
        });
        return list;
    }
}
